package com.example.feature.demo.controller;

import com.example.feature.demo.dto.FileDto;
import com.example.feature.demo.service.FileService;
import com.example.feature.demo.util.FileUtil;
import com.zhou.common.constant.BaseConstant;
import com.zhou.common.dto.ResponseDto;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * java类简单作用描述
 */
@RestController
@RequestMapping(value = "/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    FileUtil fileUtil;

    @Autowired
    FileService fileService;

    @ApiOperation(value = "下载文件模板")
    @PostMapping("/downloadModel")
    public void downloadModel(@RequestBody FileDto fileDto, HttpServletRequest httpRequest) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();

        if (fileDto == null || fileDto.getModelType() == null) {
            throw new RuntimeException("参数不能为空");
        }
        String filename = "用户手机号.xlsx";
        if (fileDto.getModelType() == 1) {
            filename = "IP列表.csv";
        } else if (fileDto.getModelType() == 2) {
            filename = "批量手动退款列表.xlsx";
        } else if (fileDto.getModelType() == 3) {
            filename = "用户手机号.xlsx";
        } else if (fileDto.getModelType() == 4) {
            filename = "花渝会员列表.xlsx";
        }

        fileUtil.downFile(httpRequest, response, filename);
    }

    @ApiOperation(value = "批量导入会员")
    @PostMapping("/batchImport")
    public ResponseDto batchImport(MultipartFile file) {
        logger.info("batchImport begin, the Condition is: ", file);
        fileService.batchImport(file);
        return new ResponseDto(BaseConstant.DEFAULT_SUCCESS_CODE, null, BaseConstant.DEFAULT_SUCCESS_MESSAGE);
    }
}
